package com.houger.ddd.redpacket.infra.entity;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;

import java.io.Serializable;
import java.time.LocalDateTime;

/**
 * @author Houger.
 * @date 2024年04月20日 15:56.
 */
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
@DynamicInsert
@DynamicUpdate
@Entity
@Table( name ="grab_red_packet" )
public class GrabRedPacket implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String redPacketId;
    private String userId;
    private String money;
    private String grabTime;
    private String bestLuck;

    @Column(updatable = false)
    @JsonDeserialize(using = LocalDateTimeDeserializer.class)
    @JsonSerialize(using = LocalDateTimeSerializer.class)
    private LocalDateTime createTime;

    @JsonDeserialize(using = LocalDateTimeDeserializer.class)
    @JsonSerialize(using = LocalDateTimeSerializer.class)
    private LocalDateTime updateTime;

    @Version
    private Long lastVersion;

    private Boolean isDelete;

    private Long deleteId;

    // 使用 @PrePersist 注解来在实体被创建时自动填充 createdAt 字段
    @PrePersist
    protected void onCreate() {
        this.createTime = LocalDateTime.now();
        this.updateTime = this.createTime; // 初始化 updatedAt 为创建时的值
        this.isDelete=Boolean.FALSE;
        this.deleteId=0L;
    }

    // 使用 @PreUpdate 注解来在实体被更新时自动填充 updatedAt 字段
    @PreUpdate
    protected void onUpdate() {
        this.updateTime = LocalDateTime.now();
    }
}
